<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="90px" label-position="left" :rules="rules">
      <div class="examineTitle mb20">
        加班申请
      </div>
      <el-form-item label="开始时间" prop="isEmpty">
        <el-col :span="5">
          <el-date-picker type="date" placeholder="请选择" v-model="startDay" style="width: 100%;" format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"></el-date-picker>
        </el-col>
        <el-col class="line" :span="1">-</el-col>
        <el-col :span="4">
          <el-time-picker placeholder="请选择" v-model="startTime" style="width: 100%;" format="HH:mm"
                          value-format="HH:mm" @change="changetimeFn('start')"></el-time-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="结束时间" prop="isEmpty">
        <el-col :span="5">
          <el-date-picker type="date" placeholder="请选择" v-model="endDay" style="width: 100%;" format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"></el-date-picker>
        </el-col>
        <el-col class="line" :span="1">-</el-col>
        <el-col :span="4">
          <el-time-picker placeholder="请选择" v-model="endTime" style="width: 100%;" format="HH:mm"
                          value-format="HH:mm" @change="changetimeFn('end')"></el-time-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="时长(小时)" prop="isEmpty">
        <el-input v-model="hours" placeholder="时长" disabled></el-input>
        <div class="tips-rule">
          根据排班自动计算时长
        </div>
      </el-form-item>
      <el-form-item label="加班原因" prop="isEmpty">
        <el-input type="textarea" v-model="form.content" placeholder="加班原因"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {overtimeAdd} from "@/api/system/leave"
import {mapGetters} from 'vuex'

export default {
  name: "index",
  components: {},
  props: ['flowData', 'deptOptions', 'workDay'], // workDay 固定班制 时间
  data() {
    return {
      activeName: 'first',
      form: {
        userId: 0, //用户id
        startTime: '', //开始时间
        endTime: '', //结束时间
        time: '', // 时长
        content: '', //原因
        flowId: 0, //审核流程id
        isEmpty: '1'
      },
      rules: {
        isEmpty: [
          {required: true, message: '不能为空', trigger: 'blur'},
        ],
      },
      startDay: '',
      startTime: '',
      endDay: '',
      endTime: '',
      hours: '',
      flagLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'deptId',
      'userId'
    ]),
  },
  watch: {
    startDay() {
      this.changeDayTime()
    },
    endDay() {
      this.changeDayTime()
    },
  },
  created() {
  },
  methods: {
    onSubmit(flowline) {
      console.log('submit!');
      if(!this.startDay || !this.startTime || !this.endDay || !this.endTime){
        this.$message.error('请正确选择加班时间')
        return
      }
      if(!this.form.content){
        this.$message.error('填写加班事由')
        return
      }
      let query_ = JSON.parse(JSON.stringify(this.form))
      let that =this
      let examinelog_ = []
      for (let item of flowline) {
        let userData_ = []
        if (item.userData) {
          for (let user of item.userData) {
            userData_.push(user.id)
          }
        }
        examinelog_.push({
          // item.assignedType
          examineId: 0, // 审核id
          name: item.exaName, // 名称
          content: '', //
          userIds: userData_.join(','), //  步骤审核人
          isExamine: 0, //  0-待审核1-通过2-驳回
          type: item.moreUserSign ? (item.moreUserSign == 'AND' ? 1 : 2) : 0, // 全部用户审核，1个用户审核
          isAuto: item.assignedType == 'AUTO_PASS' ? 1 : 0, // 是否直接通过0否1是
          style: item.assignedType == 'CC' ? 2 : 1, // 1 审核 2 抄送
        })
      }
      query_.userId = this.userId
      query_.startTime = `${this.startDay} ${this.startTime}:00`
      query_.endTime = `${this.endDay} ${this.endTime}:00`
      query_.examineLog = examinelog_
      query_.flowId = this.flowData ? this.flowData.id : 0
      delete query_.isEmpty
      if(this.flagLoading){
        return
      }
      this.flagLoading = true
      this.$modal.loading("正在保存中，请稍候...");
      overtimeAdd(query_).then(res => {
        console.log('res===>', res)
        this.$message.success('提交成功')
        this.reset()
      })
      setTimeout(()=>{
        that.flagLoading = false
      }, 1000)
    },
    reset() {
      this.form = {
        userId: 0, //用户id
        startTime: '', //开始时间
        endTime: '', //结束时间
        time: '', // 时长
        content: '', //原因
        file: '', //附件
        flowId: 0, //审核流程id
        isEmpty: '1'
      }
      this.startDay = ''
      this.startTime = ''
      this.endDay = ''
      this.endTime = ''
      this.hours = ''
      this.$emit('reset')
      this.$modal.closeLoading();
    },
    changetimeFn(type) {
      console.log('上班时间状态信息', this.workDay)
      // // workDay 序列号 5 代表 周六 6 代表周天 固定班制
      // // this.changeDayTime()
      // let firstDayOfMonth = new Date(this.startDay)
      // // //该月第一天是周几?0表示周日，1表示周一...6表示周六
      // let dayWeek = firstDayOfMonth.getDay()
      // if (this.workDay[dayWeek ? dayWeek - 1 : 6]) {
      //   // 上班时间 comeTime1 , 下班时间 outTime1
      // } else {
      //   console.log('当天休息：')
      // }
      // console.log('星期几', dayWeek)
      this.changeDayTime()
    },
    // checkTime(){
    //   if (this.startDay && this.startTime && this.endDay && this.endTime) {
    //     let start_Time = new Date(`${this.startDay} ${this.startTimeSon}`).getTime() // 开始时间时间戳
    //     let end_Time = new Date(`${this.endDay} ${this.endTime}`).getTime() // 开始时间时间戳
    //     let work_time = new Date(`${this.startDay} ${this.startTimeSon}`).getTime() // 开始时间时间戳
    //   }
    // },
    // 比较两个时间相隔几天，几小时
    changeDayTime() {
      if (this.startDay && this.startTime && this.endDay && this.endTime) {
        let checkTime_s = new Date(`${this.startDay} ${this.startTime}`).getTime() // 加班开始时间
        let checkTime_e = new Date(`${this.endDay} ${this.endTime}`).getTime() // 加班结束时间
        if (checkTime_e < checkTime_s) {
          this.$message.error('请正确选择时间区间')
          return
        }
        if (checkTime_e == checkTime_s) {
          this.$message.error('加班时长不能为0')
          return
        }
        let date1 = new Date(this.startDay);
        // 创建第二个时间对象
        let date2 = new Date(this.endDay);
        // 计算两个时间相隔的天数
        let diffInDays = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));

        // 获取两个时间之间的每一天
        let leaveDay_ = []
        // let hour = 0 // 一共几小时
        // let minute = 0 // 一共几分钟
        for (let i = 0; i < diffInDays + 1; i++) {
          let currentDay = new Date(date1.getTime() + (i * 24 * 60 * 60 * 1000));
          let day_ = currentDay.toLocaleString()
          let a_ = day_.split(' ')[0].split('/')
          let day_time = a_.map(Number)
          let firstDayOfMonth = new Date(a_[0], a_[1] - 1, a_[2])
          // //该月第一天是周几?0表示周日，1表示周一...6表示周六
          let dayWeek = firstDayOfMonth.getDay()
          leaveDay_.push({
            week: dayWeek,
            day: a_.join('-')
          })
          // 判断是否是工作日是有时间段上班的
        }
        // console.log('加班几天', leaveDay_)
        let rest_ = [] // 加班时段
        for (let index in leaveDay_) {
          // console.log('index=>', index)
          let item = leaveDay_[index]
          let workDay = this.workDay[item.week ? item.week - 1 : 6]
          let day_start = new Date(`${item.day} ${this.startTime}`).getTime() // 加班开始时间
          let day_end = new Date(`${item.day} ${this.endTime}`).getTime() // 加班结束时间
          let start_t = ''
          let end_t = ''

          if (workDay) {
            let work_start = new Date(`${item.day} ${workDay.comeTime1}`).getTime() // 上班时间
            let work_end = new Date(`${item.day} ${workDay.outTime1}`).getTime() // 下班时间
            // console.log('上班时间不算加班') // 上班时间 comeTime1 , 下班时间 outTime1
            if (leaveDay_.length == 1) {
              // 当天时间判断
              // 分段判断加班时间的区间位置
              if (day_start < work_start) {
                start_t = day_start
                if (day_end < work_start) {
                  end_t = day_end
                  rest_.push([start_t, end_t])
                } else if (day_end > work_start && day_end > work_end) {
                  rest_.push([start_t, work_start])
                }
              } else if (day_start > work_start) {
                if (day_start < work_end) {
                  start_t = work_end
                } else if (day_start > work_end) {
                  start_t = day_start
                }
                if (day_end > work_end) {
                  rest_.push([start_t, day_end])
                }
              }
            } else if (leaveDay_.length == 2) {
              if (Number(index)) {
                if (day_end < work_start) {
                  rest_.push([new Date(`${item.day} 00:00:00`).getTime(), day_end])
                } else if (day_end > work_start && day_end < day_end) {
                  rest_.push([new Date(`${item.day} 00:00:00`).getTime(), work_start])
                } else if (day_end > work_end) {
                  rest_.push([new Date(`${item.day} 00:00:00`).getTime(), work_start])
                  rest_.push([work_end, day_end])
                }
              } else {
                if (day_start < work_start) {
                  rest_.push([day_start, work_start])
                  rest_.push([work_end, new Date(`${item.day} 23:59:59`).getTime()])
                } else if (day_start > work_start && day_start < work_end) {
                  rest_.push([work_end, new Date(`${item.day} 23:59:59`).getTime()])
                } else if (day_start > work_end) {
                  rest_.push([day_start, new Date(`${item.day} 23:59:59`).getTime()])
                }
              }
            } else {

            }
          } else {
            console.log('休息时间全天都算')
          }
        }
        let count_ = 0
        for (let time_ of rest_) {
          let date1 = new Date(time_[0]);
          let date2 = new Date(time_[1]);

          let diffInMilliseconds = Math.abs(date2 - date1); // 获取两个日期对象之间的毫秒数差值（正负都包括）
          let minutesDiff = Math.floor((diffInMilliseconds / (60 * 1000))); // 分钟

          count_ = count_ + minutesDiff
        }
        let minutesDiff_m = count_ % 60
        let number_ = parseFloat(`${Math.floor(count_ / 60)}.${minutesDiff_m < 10 ? '0' + minutesDiff_m : minutesDiff_m}`)
        console.log('加班时长', count_, number_)
        if (leaveDay_.length > 2) {
          this.$message.error('加班时长不得超过12小时')
          this.startDay = ''
          this.startTime = ''
          this.endDay = ''
          this.endTime = ''
          return
        }
        this.hours = number_
        this.form.time = count_
      }
    },
  }
}
</script>

<style scoped>
.examineTitle {
  font-size: 20px;
  font-weight: bold;
}

.line {
  text-align: center;
}

.tips-rule {
  color: #999;
  font-size: 12px;
}

.tips-rule span {
  color: #2a99ff;
  cursor: pointer;
}
</style>
